﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;

namespace HostingRedisServer
{
    public class RedisHostedService : BackgroundService
    {
        private readonly IRedisServer _redisServer;
        private readonly ILogger<RedisHostedService> _logger;
        private IConnectionMultiplexer? _redis;

        public RedisHostedService(IRedisServer redisServer, ILogger<RedisHostedService> logger)
        {
            _redisServer = redisServer;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                await _redisServer.StartAsync();
                _redis = await ConnectionMultiplexer.ConnectAsync(_redisServer.ConnectionString);// 连接到 Redis
                var db = _redis.GetDatabase();
                _logger.LogInformation("成功连接到 Redis 服务器");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Redis 服务发生错误");
            }
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("正在停止 Redis 服务...");
            if (_redis != null)
            {
                await _redis.CloseAsync();
                _redis.Dispose();
            }
            await _redisServer.StopAsync();
            await base.StopAsync(cancellationToken);
        }
    }
}
